import time
from datetime import datetime, timedelta

from sqlalchemy.ext.asyncio import session
from sqlalchemy.orm import declarative_base
import logging
from app import db
from flask import abort
from sqlalchemy import or_, and_

Base = declarative_base()


class BusinessInformation(db.Model):
    """
    工商数据
    """
    __tablename__ = 'business_information'
    id = db.Column(db.Integer, primary_key=True)
    # 企业名称
    ent_name = db.Column(db.String(500), comment='企业名称', default='', nullable=False)
    # 社会信用代码
    unisc_id = db.Column(db.String(200), comment='社会信用代码', default='', nullable=False)
    # 注册号
    reg_no = db.Column(db.String(200), comment='注册号', default='', nullable=False)
    # 法定代表人
    name = db.Column(db.String(200), comment='法定代表人', default='', nullable=False)
    # 登记机关
    reg_org_cn = db.Column(db.String(200), comment='登记机关', default='', nullable=False)
    # 企业地址
    dom = db.Column(db.String(200), comment='企业地址', default='', nullable=False)
    # 成立时间
    est_date = db.Column(db.Date, comment='成立时间', default='', nullable=False)
    # 公司类型
    ent_type_cn = db.Column(db.String(100), comment='公司类型', default='', nullable=False)
    # 注册资本
    reg_cap = db.Column(db.String(100), comment='注册资本', default='', nullable=False)
    # 登记状态
    reg_state_cn = db.Column(db.String(100), comment='登记状态', default='', nullable=False)
    # 经营范围
    op_scope = db.Column(db.String(2000), comment='经营范围', default='', nullable=False)
    # 营业时间至
    op_to = db.Column(db.String(100), comment='营业时间至', default='', nullable=False)
    # 营业时间起
    op_from = db.Column(db.String(100), comment='营业时间起', default='', nullable=False)
    updata_data = db.Column(db.Integer, default='0', comment='更新时间')

    def to_json(self):
        json_data = {
            'id': self.id,
            'ent_name': self.ent_name,
            'unisc_id': self.unisc_id,
            'reg_no': self.reg_no,
            'name': self.name,
            'reg_org_cn': self.reg_org_cn,
            'dom': self.dom,
            'est_date': self.est_date.strftime('%Y-%m-%d'),
            'ent_type_cn': self.ent_type_cn,
            'reg_cap': self.reg_cap,
            'reg_state_cn': self.reg_state_cn,
            'op_scope': self.op_scope,
            'op_to': self.op_to,
            'op_from': self.op_from,
            'updata_data': self.updata_data
        }
        return json_data


def data_treating(params):
    """
    有数据就更新，无数据就插入
    :param params:
    :return:
    """
    logging.info(f'数据库处理数据：{params}')
    try:
        data = BusinessInformation.query.filter(BusinessInformation.unisc_id == params['unisc_id']).first()
        if data:
            BusinessInformation.query.filter(BusinessInformation.unisc_id == params['unisc_id']).update(params)
            db.session.commit()
            db.session.close()
        else:
            data = BusinessInformation.query.filter(BusinessInformation.ent_name == params['ent_name']).all()
            if data:
                db.session.query(BusinessInformation).filter(BusinessInformation.ent_name == params['ent_name']).update(
                    params)
                db.session.commit()
                db.session.close()
            else:
                insert(params)
    except Exception as e:
        logging.error(e, exc_info=True)


def select_data_one(key):
    data_m = []
    time_now = str((datetime.now().date() - timedelta(days=7)).strftime('%Y-%m-%d'))
    data_filter = {
        and_(
            or_(
                BusinessInformation.unisc_id == key,
                BusinessInformation.ent_name == key
            ),
            BusinessInformation.updata_data >= int(time.mktime(time.strptime(time_now, "%Y-%m-%d")))
        )
    }
    data = BusinessInformation.query.filter(*data_filter).first()
    if data:
        data_m.append(data.to_json())
        return data_m
    else:
        return data_m


def select_data_like(key):
    """
    模糊查询
    :param key:
    :return:
    """
    data_m = []
    data_filter = {
        or_(
            BusinessInformation.unisc_id.like(key),
            BusinessInformation.ent_name.like(key)
        )
    }
    data = BusinessInformation.query.filter(*data_filter).first()
    if data:
        data_m.append(data.to_json())
        return data_m
    else:
        return data_m


def insert(params):
    """
    插入数据
    :param params:
    :return:
    """
    data = BusinessInformation(**params)
    db.session.add(data)
    db.session.commit()
    db.session.close()
